package com.loongtech.bi.action;

import com.alibaba.fastjson.JSON;
import com.loongtech.bi.entity.system.EntitySysUser;
import com.loongtech.bi.manager.system.SysUserManager;
import com.loongtech.bi.manager.system.SysUserProjectRoleManager;
import com.loongtech.bi.support.Session;
import com.loongtech.core.util.Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Controller
@Scope("session")
@RequestMapping("/user")
public class LoginBiAction extends TransferHelper {
	private static final long serialVersionUID = 1L;
    @Autowired
    private Session session;
    @Autowired
    private SysUserManager sysUserManager;
    @Autowired
    private SysUserProjectRoleManager sysUserProjectRoleManager;

    @RequestMapping(value = "login.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void login(HttpServletRequest request, HttpServletResponse response, @RequestParam String u, @RequestParam String p, String ys, String callback) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 用户名或密码为空
            if (StringUtils.isBlank(u) || StringUtils.isBlank(p)) {
                result.put("res", 2);
                printToJson(response, result, callback);
                return;
            }
            // 用户名或者密码不对
            if (!sysUserManager.login(u, p, ys)) {
                result.put("res", 3);
                printToJson(response, result, callback);
                return;
            }
            // 如果userid为空
            Integer userId = sysUserManager.getUserIdByName(u);
            if (null == userId) {
                result.put("res", 4);
                printToJson(response, result, callback);
                return;
            }

            boolean isAdmin = sysUserManager.isAdmin(userId);

            Map<String, Map<String, Set<String>>> map = isAdmin ? sysUserProjectRoleManager.getAllprojectsAllpages(userId) : sysUserProjectRoleManager.getAllprojectsAllpages(userId);

            result.put("res", "0");
            result.put("isAdmin", isAdmin);
            result.put("data", map);
            result.put("u", u);
            result.put("i", userId);
            result.put("p", "ys".equals(ys) ? Utils.md5(p) : p);

            request.getSession().setAttribute("userId", userId);
            session.setAdmin(isAdmin);
            session.setUserId(userId);
            session.setUserName(u);

            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
        }
        /*	request.getSession().setAttribute("userId", username);

    // 设置项目内session
			session.setAdmin(true);
			session.setUserId(userId);
			session.setUserName(username);
			sysLogManager.addLog(username, "登录成功,登录名为:"+username+",userId="+userId);   */


    }

    public static final String SSO_AUTHSIGN_URL = "http://sso-test.zulong.com/acs_sso/sso/authSign";
    @RequestMapping(value = "ssologin.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void ssologin(HttpServletRequest request, HttpServletResponse response, @RequestParam String timestamp, @RequestParam String appid, @RequestParam String uuid, @RequestParam String sign, String callback) {
        Map<String, Object> result = new HashMap<>();
        try {
            String uri = SSO_AUTHSIGN_URL + "?timestamp=" + timestamp + "&appid=" + appid + "&uuid=" + uuid + "&sign=" + sign;
            String res = Utils.httpGet(uri, null);

            Map resMap = JSON.parseObject(res);
            String retcode = resMap.get("retcode").toString();
            if (!"0".equals(retcode)) {
                result.put("res", 1);
                result.put("msg", "sso验证失败！");
                printToJson(response, result, callback);
                return;
            }

            String userinfo = resMap.get("userinfo").toString();
            Map userinfoMap = JSON.parseObject(userinfo);
            String u = userinfoMap.get("logincode").toString();

            // 如果userid为空
            EntitySysUser user = sysUserManager.getUserByName(u);
            if (user == null || user.getId() == null) {
                result.put("res", 4);
                printToJson(response, result, callback);
                return;
            }

            Integer userId = user.getId();
            boolean isAdmin = sysUserManager.isAdmin(userId);

            Map<String, Map<String, Set<String>>> map = isAdmin ? sysUserProjectRoleManager.getAllprojectsAllpages(userId) : sysUserProjectRoleManager.getAllprojectsAllpages(userId);
            if (map == null || map.size() <= 0) {
                result.put("res", 5);
                printToJson(response, result, callback);
                return;
            }

            result.put("res", "0");
            result.put("isAdmin", isAdmin);
            result.put("data", map);
            result.put("u", u);
            result.put("i", userId);
            result.put("p", user.getPassword());

            request.getSession().setAttribute("userId", userId);
            session.setAdmin(isAdmin);
            session.setUserId(userId);
            session.setUserName(u);

            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
        }
    }

    @RequestMapping(value = "ssologout.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void ssologout(HttpServletRequest request, HttpServletResponse response, @RequestParam String timestamp, @RequestParam String appid, @RequestParam String uuid, @RequestParam String sign, String callback) {
        Map<String, Object> result = new HashMap<>();
        try {
            String uri = SSO_AUTHSIGN_URL + "?timestamp=" + timestamp + "&appid=" + appid + "&uuid=" + uuid + "&sign=" + sign;

            System.out.println("uriii: " + uri);

            String res = Utils.httpGet(uri, null);

            System.out.println("resss: " + res);

            Map resMap = JSON.parseObject(res);
            String retcode = resMap.get("retcode").toString();
            if (!"0".equals(retcode)) {
                result.put("res", 1);
                result.put("msg", "sso验证失败！");
                printToJson(response, result, callback);
                return;
            }

            String userinfo = resMap.get("userinfo").toString();
            Map userinfoMap = JSON.parseObject(userinfo);
            String u = userinfoMap.get("logincode").toString();

            // 如果userid为空
            EntitySysUser user = sysUserManager.getUserByName(u);
            if (user == null || user.getId() == null) {
                result.put("res", 4);
                printToJson(response, result, callback);
                return;
            }

            request.getSession().removeAttribute("userId");

            result.put("res", "0");
            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
        }
    }

    /**
     * 注销登录
     *
     * @return
     * @author HivenYang
     * @date 2015年5月29日
     */
    public String logout() {
        //直接跳回到登录界面
        return "login.jsf";
    }
}